package com.summer.web.controller;
import com.summer.service.Impl.UserServiceImpl;
import com.summer.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.summer.pojo.User;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/login")
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/user")
    public String login(String username, String password, Model model, HttpSession session){
        User user = userService.selectUserByUserName(username);
        if (user!=null&&user.getPassword().equals(password)){
            session.setAttribute("user",user);
            if (user.getRoleid()==0) return "redirect:/book/adminfindAllBook";
            return "redirect:/book/userfindAllBook";
        }
        else {
            model.addAttribute("msg","账号或密码错误");
            return "login";
        }
    }

    @RequestMapping("/updateUser")
    public String updateUserById(User user){
       userService.updateUser(user);
       return "redirect:/book/adminfindAllBook";
    }
    @RequestMapping("/adminupdateUser")
    public String adminupdateUser(User user){
        userService.adminupdateUser(user);
        return "redirect:/book/adminfindAllBook";
    }
    @RequestMapping("/adminupdateUsers")
    public String adminupdateUsers(User user){
        userService.updateUser(user);
        return "redirect:/login/allUser";
    }
    @RequestMapping("/userout")
    public String userout(HttpSession session){
        session.invalidate();
        return "/login";
    }
    @RequestMapping("/allUser")
    public String allUser(Model model){
        List<User> userList = userService.selectAllUsers();
        model.addAttribute("users",userList);
        return "adminuser";
    }
    @RequestMapping("/adduser")
    public String adduser(User user){
        userService.addUser(user);
        return "redirect:/login/allUser";
    }
    @RequestMapping("/adminfindUserById")
    public String adminfindUserById(int id,Model model){
        User user = userService.selectUserByID(id);
        model.addAttribute("users",user);
        return "adminupdateuser";
    }
    @RequestMapping("/admindeleteUserById")
    public String admindeleteUserById(int id){
        userService.deleteUserById(id);
        return "redirect:/login/allUser";
    }

}
